<template>
  <div class="notices-management">
    <div class="header">
      <h2>公告管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        发布公告
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="标题">
        <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="已发布" value="published" />
          <el-option label="草稿" value="draft" />
          <el-option label="已过期" value="expired" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 公告表格 -->
    <el-table :data="noticeList" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="publish_date" label="发布时间" width="180" />
      <el-table-column prop="expire_date" label="过期时间" width="180" />
      <el-table-column prop="author" label="发布人" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 公告表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :before-close="handleClose"
    >
      <el-form ref="noticeFormRef" :model="noticeForm" :rules="noticeRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="noticeForm.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="noticeForm.content" type="textarea" :rows="5" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发布时间" prop="publish_date">
              <el-date-picker
                v-model="noticeForm.publish_date"
                type="datetime"
                placeholder="选择发布时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过期时间" prop="expire_date">
              <el-date-picker
                v-model="noticeForm.expire_date"
                type="datetime"
                placeholder="选择过期时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="status">
          <el-select v-model="noticeForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getNotices, 
  createNotice, 
  deleteNotice 
} from '@/api/system'
import type { Notice, NoticeForm } from '@/api/system'

const loading = ref(false)
const dialogVisible = ref(false)
const isAdd = ref(true)
const noticeFormRef = ref()

const searchForm = reactive({
  title: '',
  status: ''
})

const noticeForm = reactive<NoticeForm>({
  title: '',
  content: '',
  publish_date: '',
  expire_date: '',
  status: 'draft'
})

const noticeList = ref<Notice[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const noticeRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  publish_date: [{ required: true, message: '请选择发布时间', trigger: 'change' }]
}

const dialogTitle = computed(() => isAdd.value ? '发布公告' : '编辑公告')

// 获取状态标签类型
const getStatusTag = (status: string) => {
  const tags = {
    draft: 'info',
    published: 'success',
    expired: 'warning'
  }
  return tags[status as keyof typeof tags] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts = {
    draft: '草稿',
    published: '已发布',
    expired: '已过期'
  }
  return texts[status as keyof typeof texts] || status
}

// 获取公告列表
const fetchNotices = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      page_size: pagination.size,
      ...searchForm
    }
    
    const response = await getNotices(params)
    noticeList.value = response.results || []
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchNotices()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, { title: '', status: '' })
  pagination.current = 1
  fetchNotices()
}

// 新增公告
const handleAdd = () => {
  isAdd.value = true
  Object.assign(noticeForm, {
    title: '',
    content: '',
    publish_date: '',
    expire_date: '',
    status: 'draft'
  })
  dialogVisible.value = true
}

// 编辑公告
const handleEdit = (row: Notice) => {
  isAdd.value = false
  Object.assign(noticeForm, {
    title: row.title,
    content: row.content,
    publish_date: row.publish_date,
    expire_date: row.expire_date,
    status: row.status
  })
  dialogVisible.value = true
}

// 删除公告
const handleDelete = async (row: Notice) => {
  try {
    await ElMessageBox.confirm('确定删除该公告吗？', '提示', {
      type: 'warning'
    })
    
    await deleteNotice(row.id)
    ElMessage.success('删除成功')
    fetchNotices()
  } catch (error) {
    // 用户取消删除
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!noticeFormRef.value) return
  
  try {
    const valid = await noticeFormRef.value.validate()
    if (!valid) return
    
    if (isAdd.value) {
      await createNotice(noticeForm)
      ElMessage.success('发布成功')
    } else {
      // 编辑公告需要传入ID，但当前组件没有保存ID
      // 这里需要根据实际情况调整
      ElMessage.warning('编辑功能需要完善')
      return
    }
    
    dialogVisible.value = false
    fetchNotices()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  noticeFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchNotices()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchNotices()
}

onMounted(() => {
  fetchNotices()
})
</script>

<style scoped>
.notices-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>